Back to course home
0% completed
Vote For New Content
Amazon Hard Problems
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Minimum Adjacent Swaps to Make a Valid Array (medium)
Problem Statement
Given an integer array nums, return the minimum swaps required to make nums a valid array.
You can swap any two adjacent elements of the array.
An array is a valid array if it meets the following conditions:
- The
largestelement is at therightmostposition in the array. - The
smallestelement is at theleftmostposition in the array. - If there are
multiplesmallest and largest elements, any of the smallest elements should be at the leftmost position and any of the largest should be at the rightmost position.
Examples
-
Example 1:
- Input: nums =
[3, 1, 2] - Expected Output:
2 - Justification: The first swap moves
3to the second position by swapping with1, and the second swap moves3to the third position by swapping with2, positioning the smallest element (1) at the beginning and the largest element (3) at the end.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 2, 3, 4] - Expected Output:
0 - Justification: This array already meets the criteria with the smallest element (1) at the start and the largest element (4) at the end, requiring no swaps.
- Input: nums =
-
Example 3:
- Input: nums =
[3, 5, 4, 5, 1, 2] - Expected Output:
5 - Justification: The smallest element (1) requires
4swaps to move to the beginning, and after that the largest element (5) requires1swap to move to the rightmost position, considering the optimal path that minimizes overall swaps.
- Input: nums =
Try it yourself
Try solving this question here:
Java
. . . .
Solution: Minimum Deletions to Make Character Frequencies Unique
Solution: Minimum Adjacent Swaps to Make a Valid Array
Mark as Completed
On this page
Problem Statement
Examples
Try it yourself